package com.haotunet.app.goldtreasure.views;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.enums.KeyboardEnum;
import com.haotunet.app.goldtreasure.enums.KeyboardEnum.ActionEnum;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.CardInfo;
import com.haotunet.app.goldtreasure.model.CardModel;
import com.haotunet.app.goldtreasure.model.OrderInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.other.Interface.OnValueSetClickListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.utils.Utils;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import static com.haotunet.app.goldtreasure.enums.KeyboardEnum.ActionEnum.add;
import static com.haotunet.app.goldtreasure.enums.KeyboardEnum.del;


/**
 * Dialog
 *
 * @author
 */
@SuppressLint("InflateParams")
public class PayPasswordView implements OnClickListener, NumberKeyboardView.OnNumberClickListener, PasswordTextView.onClickPasteListener {

    private PasswordTextView box1;
    private PasswordTextView box2;
    private PasswordTextView box3;
    private PasswordTextView box4;
    private PasswordTextView box5;
    private PasswordTextView box6;
    private TextView title;
    private LinearLayout code;
    private LinearLayout inputLayout;
    private LinearLayout keyboard;
    private LinearLayout successTip;
    private ImageView cancle;
    private TextView codePhone;
    private TextView codeCountDown;
    private TextView changePhone;
    private NumberKeyboardView keyboardView;
    private ArrayList<String> mList = new ArrayList<String>();
    private View mView;
    private CardInfo cardInfo;
    private Activity mContext;
    private boolean isFirst = true;
    private String firstPwd, SecondPwd;
    private int mType;
    private int mFlag;
    private OnPayListener mListener;
    private ShareStore shareStore;
    private OrderInfo orderInfo;
    private String orderPrice;
    private Timer timer;
    private int curTime;

    private Handler doActionHandler = new Handler() {
        @SuppressWarnings("deprecation")
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    if (curTime == 0) {
                        timer.cancel();
                        codeCountDown.setText("重新获取");
                        codeCountDown.setTextColor(mContext.getResources().getColor(R.color.color_black));
                        codeCountDown.setEnabled(true);
                        codeCountDown.setBackground(mContext.getResources().getDrawable(R.drawable.shape_payview_get_code));
                        codeCountDown.setTextColor(mContext.getResources().getColor(R.color.color_blue));
                    } else {
                        codeCountDown.setText(curTime + "s后重发");
                        codeCountDown.setBackground(mContext.getResources().getDrawable(R.drawable.shape_payview_has_get_code));
                        codeCountDown.setTextColor(mContext.getResources().getColor(R.color.color_8c8c8c));
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    public PayPasswordView(int type, int flag, Activity mContext, OrderInfo info, String price, CardInfo cardInfo) {
        getDecorView(type, flag, mContext, info, price, cardInfo);
    }

    public static PayPasswordView getInstance(int type, int flag, Activity mContext, OrderInfo info, String price,
                                              CardInfo cardInfo, OnPayListener listener) {
        return new PayPasswordView(type, flag, mContext, info, price, cardInfo);
    }

    public void getDecorView(int type, int flag, Activity mContext, OrderInfo info, String price, CardInfo cardInfo) {
        this.mContext = mContext;
        this.mType = type;
        this.mFlag = flag;
        this.orderInfo = info;
        this.orderPrice = price;
        this.cardInfo = cardInfo;
        initView();
    }

    private void initView() {
        mView = LayoutInflater.from(mContext).inflate(R.layout.item_paypassword, null);
        shareStore = new ShareStore(mContext);
        box1 = (PasswordTextView) mView.findViewById(R.id.pay_box1);
        box2 = (PasswordTextView) mView.findViewById(R.id.pay_box2);
        box3 = (PasswordTextView) mView.findViewById(R.id.pay_box3);
        box4 = (PasswordTextView) mView.findViewById(R.id.pay_box4);
        box5 = (PasswordTextView) mView.findViewById(R.id.pay_box5);
        box6 = (PasswordTextView) mView.findViewById(R.id.pay_box6);
        title = (TextView) mView.findViewById(R.id.pay_title);
        code = (LinearLayout) mView.findViewById(R.id.code_layout);
        inputLayout = (LinearLayout) mView.findViewById(R.id.pwd_layout);
        keyboard = (LinearLayout) mView.findViewById(R.id.keyboard);
        successTip = (LinearLayout) mView.findViewById(R.id.success_tip_layout);
        codePhone = (TextView) mView.findViewById(R.id.code_conact_phone);
        codeCountDown = (TextView) mView.findViewById(R.id.code_countdown);
        changePhone = (TextView) mView.findViewById(R.id.change_phone);
        cancle = (ImageView) mView.findViewById(R.id.iv_cancle);
        keyboardView = (NumberKeyboardView) mView.findViewById(R.id.view_keyboard);
        if (mFlag == 1) {
            cancle.setBackground(mContext.getResources().getDrawable(R.drawable.return_small));
        } else {
            cancle.setBackground(mContext.getResources().getDrawable(R.drawable.heise));
        }
        if (mType == 1) {
            title.setText("请设置交易密码");
        } else if (mType == 2) {
            title.setText("请输入交易密码");
            codeCountDown.setVisibility(View.VISIBLE);
            codeCountDown.setText("忘记密码?");
            codeCountDown.setBackground(null);
            codeCountDown.setTextColor(mContext.getResources().getColor(R.color.color_red));
            codeCountDown.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        } else {
            title.setText("请输入短信验证码");
            code.setVisibility(View.VISIBLE);
            codeCountDown.setVisibility(View.VISIBLE);
        }
        if (mType == 3) {
            if (shareStore.getInt(Strs.IS_HAD_BANK_CARD, 0) == 1) {
                getBankCardInfo();
            } else {
                codePhone.setText("已发送验证码至" + Utils.hideMidFourPhoneNum(cardInfo.getPhone()) + "，请查收");
                setTimerTask();
            }
        }
        setListener();
    }

    private void setListener() {
        codeCountDown.setOnClickListener(this);
        changePhone.setOnClickListener(this);
        cancle.setOnClickListener(this);
        keyboardView.setOnNumberClickListener(this);
        box1.setClickOnPasteListener(this);
        box2.setClickOnPasteListener(this);
        box3.setClickOnPasteListener(this);
        box4.setClickOnPasteListener(this);
        box5.setClickOnPasteListener(this);
        box6.setClickOnPasteListener(this);
    }


    private void parseActionType(KeyboardEnum type) {
        if (type.getType() == add) {
            if (mList.size() < 6) {
                mList.add(type.getValue());
                updateUi();
            }
        } else if (type.getType() == ActionEnum.delete) {
            if (mList.size() > 0) {
                mList.remove(mList.get(mList.size() - 1));
                updateUi();
            }

        } else if (type.getType() == ActionEnum.longClick) {
            mList.clear();
            updateUi();
        }

    }

    private void updateUi() {
        if (mList.size() == 0) {
            box1.setText("");
            box2.setText("");
            box3.setText("");
            box4.setText("");
            box5.setText("");
            box6.setText("");
        } else if (mList.size() == 1) {
            box1.setText(mList.get(0));
            box2.setText("");
            box3.setText("");
            box4.setText("");
            box5.setText("");
            box6.setText("");
        } else if (mList.size() == 2) {
            box1.setText(mList.get(0));
            box2.setText(mList.get(1));
            box3.setText("");
            box4.setText("");
            box5.setText("");
            box6.setText("");
        } else if (mList.size() == 3) {
            box1.setText(mList.get(0));
            box2.setText(mList.get(1));
            box3.setText(mList.get(2));
            box4.setText("");
            box5.setText("");
            box6.setText("");
        } else if (mList.size() == 4) {
            box1.setText(mList.get(0));
            box2.setText(mList.get(1));
            box3.setText(mList.get(2));
            box4.setText(mList.get(3));
            box5.setText("");
            box6.setText("");
        } else if (mList.size() == 5) {
            box1.setText(mList.get(0));
            box2.setText(mList.get(1));
            box3.setText(mList.get(2));
            box4.setText(mList.get(3));
            box5.setText(mList.get(4));
            box6.setText("");
        } else if (mList.size() == 6) {
            box1.setText(mList.get(0));
            box2.setText(mList.get(1));
            box3.setText(mList.get(2));
            box4.setText(mList.get(3));
            box5.setText(mList.get(4));
            box6.setText(mList.get(5));
            if (mType == 1) {
                if (isFirst) {
                    String payValue = "";
                    for (int i = 0; i < mList.size(); i++) {
                        payValue += mList.get(i);
                    }
                    firstPwd = payValue;
                    mList.clear();
                    updateUi();
                    title.setText("请确认交易密码");
                    isFirst = false;
                    // listener.onSurePay(payValue);
                } else {
                    String payValue = "";
                    for (int i = 0; i < mList.size(); i++) {
                        payValue += mList.get(i);
                    }
                    SecondPwd = payValue;
                    comParePwd();
                }
            } else {
                String payValue = "";
                for (int i = 0; i < mList.size(); i++) {
                    payValue += mList.get(i);
                }
                mListener.onSurePay(payValue);
            }
        }
    }

    private void comParePwd() {
        if (firstPwd.equals(SecondPwd)) {
            setTradingPwd(firstPwd);
        } else {
            isFirst = true;
            mList.clear();
            updateUi();
            title.setText("请设置交易密码");
            UIHelper.showToast(mContext, "两次密码不一致,请重新输入!");
        }
    }

    private void setTradingPwd(final String pwd) {
        ActionUtil actionUtil = new ActionUtil(mContext);
        actionUtil.setTradingPwd(pwd);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (model == null) {
                    UIHelper.showToast(mContext, mContext.getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(mContext, mContext.getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(mContext, model.getErrorMsg());
                        isFirst = true;
                        mList.clear();
                        updateUi();
                        title.setText("请设置交易密码");
                    }
                } else {
                    shareStore.putInt(Strs.IS_HAD_TRADING_PWD, 1);
                    shareStore.commit();
                    mListener.onSurePay(pwd);
                }
            }
        });
    }

    @Override
    public void onNumberReturn(String number) {
        switch (number) {
            case "0":
                parseActionType(KeyboardEnum.zero);
                break;
            case "1":
                parseActionType(KeyboardEnum.one);
                break;
            case "2":
                parseActionType(KeyboardEnum.two);
                break;
            case "3":
                parseActionType(KeyboardEnum.three);
                break;

            case "4":
                parseActionType(KeyboardEnum.four);
                break;
            case "5":
                parseActionType(KeyboardEnum.five);
                break;
            case "6":
                parseActionType(KeyboardEnum.six);
                break;
            case "7":
                parseActionType(KeyboardEnum.seven);
                break;
            case "8":
                parseActionType(KeyboardEnum.eight);
                break;
            case "9":
                parseActionType(KeyboardEnum.nine);
                break;
        }
    }

    public View getView() {
        return mView;
    }

    @Override
    public void onNumberDelete() {
        parseActionType(del);
    }

    @Override
    public void onclickPaste() {
        ClipboardManager cmb = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        String pasteString = cmb.getText().toString();//获取粘贴信息
        if (!TextUtils.isEmpty(pasteString)) {
            if (pasteString.length() == 6) {
                box1.setText(pasteString.substring(0, 1));
                mList.add(pasteString.substring(0, 1));
                box2.setText(pasteString.substring(1, 2));
                mList.add(pasteString.substring(1, 2));
                box3.setText(pasteString.substring(2, 3));
                mList.add(pasteString.substring(2, 3));
                box4.setText(pasteString.substring(3, 4));
                mList.add(pasteString.substring(3, 4));
                box5.setText(pasteString.substring(4, 5));
                mList.add(pasteString.substring(4, 5));
                box6.setText(pasteString.substring(5, 6));
                mList.add(pasteString.substring(5, 6));
                mListener.onSurePay(pasteString);
            }
        }
    }

    public interface OnPayListener {
        void onCancelPay();

        void onSurePay(String password);
    }


    public void showSuccessUi() {
        title.setText("交易成功");
        keyboard.setVisibility(View.GONE);
        successTip.setVisibility(View.VISIBLE);
    }

    public void clearUi() {
        mList.clear();
        updateUi();
    }

    public void setErrorTip(String text) {
        code.setVisibility(View.VISIBLE);
        codePhone.setText(text);
    }

    public void setOnPayListener(OnPayListener listener) {
        mListener = listener;
    }

    private void getBankCardInfo() {
        ActionUtil actionUtil = new ActionUtil(mContext);
        actionUtil.getMyBankCardList();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                CardModel cardModel = (CardModel) model;
                if (cardModel == null) {
                    UIHelper.showToast(mContext, mContext.getString(R.string.rank_fail));
                    return;
                }
                if (cardModel.getErrorMsg() != null) {
                    UIHelper.showToast(mContext, cardModel.getErrorMsg());
                } else {
                    cardInfo = cardModel.getBankCards().get(0);
                    getOrderVericode(cardInfo.getPhone());
                }
            }
        });

    }

    private void getOrderVericode(final String phone) {
        ActionUtil actionUtil = new ActionUtil(mContext);
        actionUtil.getPayCode(orderInfo.getOrderNo(), cardInfo.getRealName(), cardInfo.getCardNo(),
                cardInfo.getIdCard(), phone, orderPrice, cardInfo.getPayGate(), cardInfo.getSubGate());
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (model == null) {
                    UIHelper.showToast(mContext, mContext.getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(mContext, mContext.getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(mContext, model.getErrorMsg());
                    }
                } else {
                    if ("0000".equals(model.getStatus())) {
                        codeCountDown.setEnabled(false);
                        codePhone.setText("已发送验证码至" + Utils.hideMidFourPhoneNum(phone) + "，请查收");
                        setTimerTask();
                    } else {
                        setErrorTip(model.getInfo());
                        if ("20011".equals(model.getStatus())) {
                            changePhone.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
    }

    private void setTimerTask() {
        curTime = 60;
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {

                Message msg = new Message();
                msg.what = 1;
                doActionHandler.sendMessage(msg);
                curTime--;
            }
        }, 0, 1000);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.code_countdown:
                if (mType == 2) {
                    ActivityUtils.gotoForgetTradePwd(mContext, 6);
                    mListener.onCancelPay();
                } else if (mType == 3) {
                    if (cardInfo==null){
                        return;
                    }
                    getOrderVericode(cardInfo.getPhone());
                }
                break;
            case R.id.iv_cancle:
                mListener.onCancelPay();
                break;
            case R.id.change_phone:
                if (timer != null) {
                    codeCountDown.setText(mContext.getString(R.string.get_vericode));
                    codeCountDown.setTextColor(mContext.getResources().getColor(R.color.color_black));
                    codeCountDown.setEnabled(true);
                    timer.cancel();
                }
                ChangePhoneDialog phoneDialog = new ChangePhoneDialog(mContext, R.style.MyDialog);
                phoneDialog.show();
                phoneDialog.setValueSetClickListener(new OnValueSetClickListener() {

                    @Override
                    public void onValueSet(String value) {
                        getOrderVericode(value);
                    }
                });
                break;
            default:
                break;
        }
    }


}
